<?php
namespace app\zucai\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use think\Db;
use think\Exception;
use app\zucai\model\PutCash;

use app\zucai\model\Account;
use app\zucai\model\User_recharge;
/**
 * zucai 后台模块
 */
class Order extends Admin
{
    /**
     * 订单详情首页 吴杰
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $fla = Db::name('admin_user')->field('id,role')->where('id', is_signin())->find();
        $btn_access = [
            'title' => '删除',
            'icon' => 'fa fa-times-circle-o',
            'class' => 'btn btn-xs btn-danger ajax-get confirm',
            'href' => url('delet', ['id' => '__id__']),
            'data-title' => '真的要删除吗？'
        ];
        $btn = [
            'title' => '删除',
            'icon' => 'fa fa-times-circle-o',
            'class' => 'btn btn-danger ajax-post confirm',
            'href' => url('alldelet')
        ];
		$dat = [
            'title' => '确认出票',
            'icon' => 'fa fa-times-circle-o',
            'class' => 'btn btn-danger ajax-post confirm',
            'href' => url('conten')
		
        ];
		// Excel导出
        $btn_table = [
            'title' => '导出订单记录',
            'icon' => 'fa fa-fw fa-table',
            'href' => url('excel_get'),
            'class' => 'btn btn-success  confirm'
        ];
		$id_user=Db::name('user')->column('id,name');
        if ($fla['role'] == 1) {
			
            $data_list = Db::name('admin_order')->where($this->getMap())
                ->order($this->getOrder('id DESC'))
                ->paginate();
				 return ZBuilder::make('table')
                ->setTableName('admin_order')
                ->addOrder('id,trano,beishu,itemcount,oddtime,mode')
				->addTimeFilter('oddtime')
				->addFilter('pid',$id_user)
                ->setSearch(['id' => 'ID', 'username' => '用户名', 'trano' => '订单号'],'','',true)// 设置搜索参数				 
                ->addTopButton('custom', $btn)
				->addTopButton('custom', $dat)
				->addTopButtons(['table' => $btn_table])
                ->addRightButton('custom', $btn_access)// 添加删除按钮
                ->addRightButtons(['edit'=>array('title'=>'详情','icon'=>'fa fa-eye')])
                ->addColumns([
			    ['id', 'ID'],
				['nickname', '代理商'],
                    ['pid', '跟单对象', 'callback', function ($pid) {
                        $uname = Db::name('user')->where('id', $pid)->field('name')->find();
                        if ($uname) {
                            return $uname['name'];
                        } else {
                            return '无';
                        }
                    }],
                    ['type', '类型', config('orderplay')],
                    ['name', '用户名'],
                    ['isdraw', '订单状态', config('ordertype')],
                    ['trano', '订单号'],

                    ['choicetype', '玩法'],
                    ['beishu', '倍数'],
                    ['itemcount', '投注金额'],
                    ['oddtime', '投注时间'],
                    ['mode', '获奖奖金'],
                    ['amount', '中奖注数'],
                    ['okamount', '实获金额'],
                    ['right_button', '操作', 'btn'],
			])
                ->addFilter('isdraw', config('ordertype'))
                ->addFilter('type', config('orderplay'))
                ->addFilter('dan', config('orderdan'))
                ->addFilter('trano,type')
                ->addFilter('caizhong')
                ->addFilter('name')

                ->addFilter('playtitle')
                ->addFilter('dan')
                ->setColumnWidth('id', 40)
                ->setColumnWidth('nickname', 60)
                ->setColumnWidth('type', 50)
				->setColumnWidth('pid,name', 95)
                ->setColumnWidth('choicetype,amount', 60)
                ->setColumnWidth('right_button', 70)
                ->setColumnWidth('mode,isdraw,itemcount,okamount', 80)
                ->setColumnWidth('trano', 120)
                ->setColumnWidth('oddtime', 145)
                ->setColumnWidth('choice,', 220)
                ->setColumnWidth('beishu', 55)
                ->setRowList($data_list)
                ->fetch();
        }else{
		
            $data_list = Db::name('admin_order')->where($this->getMap())
                ->where('aid',$fla['id'])
                ->order($this->getOrder('id DESC'))
                ->paginate();
				 return ZBuilder::make('table')
                ->setTableName('admin_order')
                ->addOrder('id,trano,beishu,itemcount,oddtime,mode')
				->addTimeFilter('oddtime')
				->addFilter('pid',$id_user)
                ->setSearch(['id' => 'ID', 'username' => '用户名', 'trano' => '订单号'],'','',true)// 设置搜索参数				 
                ->addTopButton('custom', $btn)
				->addTopButton('custom', $dat)
				->addTopButtons(['table' => $btn_table])
                ->addRightButton('custom', $btn_access)// 添加删除按钮
                ->addRightButtons(['edit'=>array('title'=>'详情','icon'=>'fa fa-eye')])
                ->addColumns([
			    ['id', 'ID'],
                    ['pid', '跟单对象', 'callback', function ($pid) {
                        $uname = Db::name('user')->where('id', $pid)->field('name')->find();
                        if ($uname) {
                            return $uname['name'];
                        } else {
                            return '无';
                        }
                    }],
                    ['type', '类型', config('orderplay')],
                    ['name', '用户名'],
                    ['isdraw', '订单状态', config('ordertype')],
                    ['trano', '订单号'],

                    ['choicetype', '玩法'],
                    ['beishu', '倍数'],
                    ['itemcount', '投注金额'],
                    ['oddtime', '投注时间'],
                    ['mode', '获奖奖金'],
                    ['amount', '中奖注数'],
                    ['okamount', '实获金额'],
                    ['right_button', '操作', 'btn'],
			])
                ->addFilter('isdraw', config('ordertype'))
                ->addFilter('type', config('orderplay'))
                ->addFilter('dan', config('orderdan'))
                ->addFilter('trano,type')
                ->addFilter('caizhong')
                ->addFilter('name')

                ->addFilter('playtitle')
                ->addFilter('dan')
                ->setColumnWidth('id', 40)
                ->setColumnWidth('type', 50)
				->setColumnWidth('pid,name', 90)
                ->setColumnWidth('choicetype,amount', 60)
                ->setColumnWidth('right_button', 70)
                ->setColumnWidth('mode,isdraw,itemcount,okamount', 80)
                ->setColumnWidth('trano', 120)
                ->setColumnWidth('oddtime', 145)
                ->setColumnWidth('choice,', 220)
                ->setColumnWidth('beishu', 55)
                ->setRowList($data_list)
                ->fetch();
        }
		
          
    }

	 /**
     * @return mixed
     * 导出订单记录表格
     * gxq <know1111@vip.qq.com>
     */
    public function excel_get()
    {
        $ispost = $this->request->isPost();
        if ($ispost) {
            $post = $this->request->post();
            if (!$post) $this->error('违规操作');

            if (!isset($post['time'])) $this->error('请选择时间范围');
            if (!$post['time'][0] || !$post['time'][1]) $this->error('请选择时间范围');

            $time1 = $post['time'][0];
            $time2 = $post['time'][1];
			
           
            
                $data = Db::name('admin_order')->
                where('oddtime', '>=', $time1)
                    ->where('oddtime', '<=', $time2)
                    ->where('aid', is_signin())
                    ->select();
            
            $user2 = array();
            foreach ($data as $k => $v) {
                $user2[$k][1] = $v['name'];
                $user2[$k][2] = $v['trano'];
                $user2[$k][3] = $v['itemcount'];
                $user2[$k][4] = $v['beishu'];
                $user2[$k][5] = $v['choicetype'];
                $user2[$k][6] = $v['mode'];
                $user2[$k][7] = $v['okamount'];
				$user2[$k][8] = $v['oddtime'];
				
				 switch ($v['isdraw']) {
                    case 0:
                        $user2[$k][9] = '待出票';
                        break;
                    case 1:
                        $user2[$k][9] = '已出票';
                        break;
					case 2:
                        $user2[$k][9] = '中奖';
                        break;
                    case 3:
                        $user2[$k][9] = '未中奖';
                        break;
					case 4:
                        $user2[$k][9] = '待支付';
                        break;
                    case 5:
                        $user2[$k][9] = '已失效';
                        break;	
					 case 6:
                        $user2[$k][9] = '已删除';
                        break;		
                    default :
                        $this->error('违规操作');
                };
				 switch ($v['type']) {
                    case 0:
                        $user2[$k][10] = '认购';
                        break;
                    case 1:
                        $user2[$k][10] = '跟单';
                        break;
					
                    default :
                        $this->error('违规操作');
                };
				$flag=11;
				
            $dat=explode(',',$v['choice']);
            foreach ( $dat as $k1=>$v1){
                $dat[$k1]=explode('=>',$v1);
                $dat[$k1][1]=explode('-',$dat[$k1][1]);
				 $con=Db::name('play')->field('team,team2')->where('id',$dat[$k1][0])->find();
				 $user2[$k][$flag]=$con['team'].'-'.$con['team2'];
				 $flag++;
				 $user2[$k][$flag]='';
                foreach ($dat[$k1][1] as $k3=>$v3){
                    $dat[$k1][1][$k3]=explode('@',$v3);

					
                        if($dat[$k1][1][$k3][0]=='win'){   //判断胜负平中奖
						if($dat[$k1][1][$k3][1]!=""){
                         
                                $user2[$k][$flag]=$user2[$k][$flag].'胜负平:'.$dat[$k1][1][$k3][1].',';
                          
						}
                        }elseif($dat[$k1][1][$k3][0]=='ran'){//判断让球胜负平中奖
						if($dat[$k1][1][$k3][1]!=""){
                           
                               $user2[$k][$flag]=$user2[$k][$flag].'让球胜负平:'.$dat[$k1][1][$k3][1].',';
                           
						}
                        }elseif($dat[$k1][1][$k3][0]=='fen'){//判断比分中奖
						if($dat[$k1][1][$k3][1]!=""){
                            $user2[$k][$flag]=$user2[$k][$flag].'比分:'.$dat[$k1][1][$k3][1].',';
						}
                        }elseif($dat[$k1][1][$k3][0]=='all'){ //判断总进球数中奖
						if($dat[$k1][1][$k3][1]!=""){
                            $user2[$k][$flag]=$user2[$k][$flag].'总进球数:'.$dat[$k1][1][$k3][1].',';
						}
                        }elseif($dat[$k1][1][$k3][0]=='half'){ //判断半全场胜负平中奖
						if($dat[$k1][1][$k3][1]!=""){
                             $user2[$k][$flag]=$user2[$k][$flag].'半全场胜负平:'.$dat[$k1][1][$k3][1].',';
						}
                        
						}
				}
				
				 $flag++;
                  
                }
				            

               
            }

            $headArr = array('用户名', '订单号', '投注金额', '倍数', '玩法', '中奖金额', '实获金额','下单时间','状态','订单类型','比赛队伍','选号');
            $filename = "订单记录表";
            //dump($user2);exit;
			
            $this->getExcel($filename, $headArr, $user2);
			
        }
        return ZBuilder::make('form')
            ->addFormItems([
                ['daterange', 'time']
            ])
            ->method('post')
            ->isAjax(false)	
            ->fetch();
    }
private function getExcel($fileName, $headArr, $data)
    {
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入

        vendor('PHPExcel/Classes/PHPExcel');
        $date = date("Y_m_d", time());
        $fileName .= "_{$date}";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();

        //设置表头
        $key = ord("A");
        //print_r($headArr);exit;
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $key += 1;
        }
        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();
        //print_r($data);exit;

        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");

            foreach ($rows as $keyName => $value) {// 列写入

                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        $count = count($data) + 1;
        //重命名表
        //$objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        //$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(24);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getStyle('N1:N' . $count)->getAlignment()->setWrapText(true);
        $objPHPExcel->getActiveSheet()->getStyle('A1:N' . $count)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A1:N' . $count)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();//清除缓冲区,避免乱码

        header('Content-type: application/vnd.ms-excel;charset=utf-8;name="' . 1 . '.xls"');
        header("Content-Disposition: attachment; filename=$fileName.xls");
        header('Cache-Control: max-age=0');
//header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
//header ('Cache-Control: cache, must-revalidate');
        header('Pragma: public');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
	
    public function delet($id){
        $con=Db::name('order')->field('isdraw')->where('id',$id)->find();
        if($con['isdraw']==0 || $con['isdraw']==1){
            return $this->success('该订单还未结算，不允许删除！');;
        }else {

            $uname = Db::name('order')->where('id', $id)->update(['isdraw' => 6]);
            if ($uname > 0) {
                return $this->success('删除成功');;
            } else {
                return $this->success('删除失败');;
            }
        }
    }
	//出票确认
    public function conten(){
       $ids=$_POST['ids'];
	   $flag=0;
       foreach ($ids as $k=>$value){
		    $cont=Db::name('order')->field('isdraw')->where('id',$value)->find();
			if($cont['isdraw']==0){
           $con=Db::name('order')->where('id',$value)->update(['isdraw'=>1]);
           if($con<1){
			   $flag++;
             
           }
			}
       }
        if($flag==0){
            return $this->success('出票更新成功');;
        }else{
            return $this->success('共有'.$flag.'张订单未出票成功！');;
        }
    }
    //批量伪删除
    public function alldelet(){
       $ids=$_POST['ids'];
       foreach ($ids as $k=>$value){
           $con=Db::name('order')->field('isdraw')->where('id',$value)->find();
           if($con['isdraw']==0 || $con['isdraw']==1){
               return $this->success('id为'.$value.'的订单还未结算，不允许删除！');;
           }else {
               $uname = Db::name('order')->where('id', $value)->update(['isdraw' => 6]);
           }
       }
        if($uname>0){
            return $this->success('删除成功');;
        }else{
            return $this->success('删除失败');;
        }
    }
    //编辑操作
    public function edit($id=0){
        $date=Db::name('order')->where('id',$id)->find();
        $date['choice']=explode(',',$date['choice']);

        $con=[];
        foreach ($date['choice']as $k=>$v) {
            $date['choice'][$k] = explode('=>', $v);
            $date['choice'][$k][1] = explode('-', $date['choice'][$k][1]);

            $cont = Db::name('play')->where('id', $date['choice'][$k][0])->find();

            $con[$k] = $cont['title'] . "--" . $cont['ftitle'] . "  比赛队伍：" . $cont['team'] . "->" . $cont['team2'] . "&nbsp;&nbsp;&nbsp;选项=>";
            foreach ($date['choice'][$k][1] as $k3 => $v3) {
                $date['choice'][$k][1][$k3] = explode('@', $v3);

                if ($date['choice'][$k][1][$k3][0] == 'win' && $date['choice'][$k][1][$k3][1]!='') {
                    $con[$k] = $con[$k] . '胜平负：' . $date['choice'][$k][1][$k3][1] . ";&nbsp;&nbsp;";
                } elseif ($date['choice'][$k][1][$k3][0] == 'ran' && $date['choice'][$k][1][$k3][1]!='') {
                    $con[$k] = $con[$k] . '让球胜平负：' . $date['choice'][$k][1][$k3][1] . ";&nbsp;&nbsp;";
                } elseif ($date['choice'][$k][1][$k3][0] == 'fen' && $date['choice'][$k][1][$k3][1]!='') {
                    $con[$k] = $con[$k] . '比分：' . $date['choice'][$k][1][$k3][1] . ";&nbsp;&nbsp;";
                } elseif ($date['choice'][$k][1][$k3][0] == 'all' && $date['choice'][$k][1][$k3][1]!='') {
                    $con[$k] = $con[$k] . '总进球数：' . $date['choice'][$k][1][$k3][1] . ";&nbsp;&nbsp;";
                } elseif ($date['choice'][$k][1][$k3][0] == 'half' && $date['choice'][$k][1][$k3][1]!='') {
                    $con[$k] = $con[$k] . '半全场胜负平：' . $date['choice'][$k][1][$k3][1] . ";&nbsp;&nbsp;";
                }
            }
        }
        $date['choice']='';
        foreach ($con as $key=>$value){
            $date['choice']=$date['choice']."\n".$con[$key];
        }

        if($date['isdraw']==2){
            $arr=[
                ['static','trano','订单号'],
                ['textarea','choice','竞猜选项'],
                ['static','choicetype','玩法'],
                ['static','beishu','倍数'],
                ['static','itemcount','投注金额'],
                ['static','mode','获奖奖金'],
                ['static','amount','中奖注数'],
                ['static', 'okamount', '实获金额'],
            ];
        }else{
            $arr=[
                ['static','trano','订单号'],
                ['textarea','choice','竞猜选项'],
                ['static','choicetype','玩法'],
                ['static','beishu','倍数'],
                ['static','itemcount','投注金额'],
            ];
        }

        return ZBuilder::make('form')
            ->addFormItems($arr)
            ->setFormData($date)
            ->hideBtn('submit')
            ->fetch();

    }
}